package com.azt.data.interceptor;

import com.azt.api.pojo.Admin;
import com.azt.data.permission.MenuPermission;
import com.azt.data.utils.CommonUtil;
import com.azt.data.utils.ContextUtils;
import com.azt.data.utils.Globals;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by zouheyuan on 2017/4/13.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Admin admin = ContextUtils.getAdmin();
        String requestURI = request.getRequestURI();

        /**
         * 格式化请求路径
         */
        requestURI = requestURI.replaceAll("/{2,}", "/");
        // 判断是否登录
        if (admin == null && !excludeUrls.contains(requestURI)) {
            if (CommonUtil.isAjax(request)) {
                //ajax请求的话则403状态返回错误码
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                CommonUtil.renderJson(response, "请先登录");
            }else{
                response.sendRedirect("/login");
            }
            return false;
        }


        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            MenuPermission menuPermission = handlerMethod.getMethodAnnotation(MenuPermission.class);
            if(menuPermission == null) {
                menuPermission = handlerMethod.getBean().getClass().getAnnotation(MenuPermission.class);
            }

            if(menuPermission != null && !ContextUtils.checkFunctionPermission(requestURI)) {
                //当前没有登录，返回登录页面
                response.sendRedirect("/");
                return false;
            }
        }


        return true;
    }

    private List<String> excludeUrls;

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }
}
